﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace ThirdParty
{
    /// <summary>
    /// 微博登录处理
    /// </summary>
    public class SinaLoginHandle
    {
        /// <summary>
        /// 创建引用的AppKey
        /// </summary>
        public string AppKey { get; set; }
        /// <summary>
        /// 创建应用的AppSecret
        /// </summary>
        public string AppSecret { get; set; }
        /// <summary>
        /// 当前请求上下文控制
        /// </summary>
        RequestHelper _Request = new RequestHelper();
        /// <summary>
        /// 当获取用信息成功时触发
        /// </summary>
        public Action<SinaInfo> OnSuccess = null;
        /// <summary>
        /// 当前第一次请求时，触发
        /// </summary>
        public Action OnFirstRequest = null;
        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="AppKey">AppKey</param>
        /// <param name="AppSecret">AppSecret</param>
        public SinaLoginHandle( string AppKey,string AppSecret)
        {
            this.AppSecret = AppSecret;
            this.AppKey = AppKey;
        }
        /// <summary>
        /// 执行逻辑处理
        /// </summary>
        public void DoHandle()
        {
            HttpResponse resp = HttpContext.Current.Response;
            HttpRequest req = HttpContext.Current.Request;
            HttpServerUtility server = HttpContext.Current.Server;

            string thisUrl = req.Url.AbsoluteUri;
            string code = _Request.GetStringQuery("code");
            //第一次访问  
            if (code == "")
            {
                #region 第一步 根据appid 获取 Authorization Code  
                StringBuilder builder = new StringBuilder(500);
                builder.Append("https://api.weibo.com/oauth2/authorize?");
                builder.AppendFormat("response_type={0}", "code");
                builder.AppendFormat("&client_id={0}", this.AppKey);
                builder.AppendFormat("&redirect_uri={0}", server.UrlDecode(thisUrl));
                builder.AppendFormat("&state={0}", "tianma3798");//用于自身验证  
                builder.AppendFormat("&scope={0}", "all");
                //第一次请求，进行逻辑处理
                if (this.OnFirstRequest != null)
                {
                    this.OnFirstRequest();
                }
                resp.Redirect(builder.ToString(), false);
                return;
                #endregion
            }
            string state = _Request.GetStringQuery("state");
            //第二次访问  
            if (code != "" && state == "tianma3798")
            {
                #region 第二步 根据Authorization Code 获取Access Token 和 uid  
                StringBuilder builder = new StringBuilder(500);
                builder.Append("https://api.weibo.com/oauth2/access_token?");
                builder.AppendFormat("grant_type={0}", "authorization_code");
                builder.AppendFormat("&client_id={0}", this.AppKey);
                builder.AppendFormat("&client_secret={0}", this.AppSecret);
                builder.AppendFormat("&code={0}", code);
                builder.AppendFormat("&redirect_uri={0}", server.UrlDecode(thisUrl));
                //1.获取并解析 access_token 例如：  
                string access_token = "";
                string uid = "";
                try
                {
                    string result = NetHelper.Post(builder.ToString()); //此处微博拒绝get请求  
                    result = RegexHelper.Replace(result, "{|}|\"", "");
                    string[] temp = result.Split(',');
                    access_token = temp[0].Split(':')[1];
                    uid = temp[3].Split(':')[1];
                }
                catch (Exception ex)
                {
                    throw new Exception("解析 access_token 是出错：" + ex.Message);
                }
                #endregion

                #region 第三步 根据uid 调用微博API 获取用户信息  
                //第四步 获取用户信息  
                builder.Clear();
                builder.Append("https://api.weibo.com/2/users/show.json?");
                builder.AppendFormat("access_token={0}", access_token);
                builder.AppendFormat("&uid={0}", uid);
                builder.AppendFormat("&source={0}", this.AppSecret);
                #endregion
                try
                {
                    string userinfo = NetHelper.Get(builder.ToString()); //微博次数拒绝 post请求  
                    SinaInfo info = userinfo.JsonDeserialezer<SinaInfo>();
                    if (info == null)
                    {
                        throw new Exception("内部错误：反序列化获取SinaInfo对象时失败！");
                    }
                    info.access_token = access_token;
                    //获取数据成功，进行其他逻辑处理  
                    if (this.OnSuccess != null)
                    {
                        this.OnSuccess(info);
                    }
                }
                catch (Exception ex)
                {
                    string msg = "获取用户信息失败，--------出错原因：" + ex.Message;
                }
            }
        }
    }

}
